package com.adee.jvm;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test001_deadlock {
    static final Lock lock1 = new ReentrantLock();
    static final Lock lock2 = new ReentrantLock();

    /**
     * 使用jstack打印jvm所有线程快照
     * jstack -l -e 15428 > e:/tmp/jstak-deadlock.txt
     *
     * arthas中 thread -b命令也可检测死锁
     *
     */
    public static void main(String[] args) {

        test();
    }

    public static void test() {
        new Thread(() -> {
            lock1.lock();
            try {
                sleep(1);
                lock2.lock();
            } finally {
                lock1.unlock();
            }
        }).start();
        new Thread(() -> {
            lock2.lock();
            try {
                sleep(1);
                lock1.lock();
            } finally {
                lock2.unlock();
            }
        }).start();
    }

    static void sleep(int i) {
        try {
            TimeUnit.SECONDS.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
